<template>
  <div class="ai-chat-container">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <div class="chat-title">AI 助手</div>
      <div class="chat-actions">
        <el-button icon="Minus" circle size="small"></el-button>
        <el-button icon="Close" circle size="small"></el-button>
      </div>
    </div>

    <!-- 聊天内容区域 -->
    <div class="chat-content" ref="chatContent">
      <!-- 欢迎消息 -->
      <div class="message-wrapper ai-message">
        <div class="avatar">
          <img src="@/views/AI/images/ai-avatar.png" alt="AI Avatar">
        </div>
        <div class="message">
          <p>你好！我是你的智能助手涛涛。有什么我可以帮助你的吗？</p>
        </div>
      </div>

      <!-- 消息列表 - 动态渲染 -->
      <div v-for="(msg, index) in messages" :key="index"
        :class="['message-wrapper', msg.isUser ? 'user-message' : 'ai-message']">
        <div class="avatar">
          <img :src="msg.isUser ? '/src/views/AI/images/my.jpg' : '/src/views/AI/images/ai-avatar.png'" alt="Avatar">
        </div>
        <div class="message">
          <p>{{ msg.content }}</p>
          <!-- 视频播放区域 -->
          <video v-if="msg.videoUrl" controls class="video-player">
            <source :src="msg.videoUrl" type="video/mp4">
            您的浏览器不支持视频播放
          </video>
          <!-- 上传到快手按钮 -->
          <el-button v-if="msg.videoUrl" type="primary" size="small" class="upload-btn"
            @click="showUploadDialog(msg.videoUrl, index)">
            发布到快手
          </el-button>
          <!-- 发布到抖音按钮 -->
          <el-button v-if="msg.videoUrl" type="primary" size="small" class="upload-btn"
            @click="showDouyinUploadDialog(msg.videoUrl, index)">
            发布到抖音
          </el-button>
          <!-- 发布到小红书按钮 -->
          <el-button v-if="msg.videoUrl" type="primary" size="small" class="upload-btn"
            @click="showXiaohongshuVideoUploadDialog(msg.videoUrl || '', msg.coverUrl || '', index)">
            发布到小红书
          </el-button>
          <!-- 图片显示区域 -->
          <img v-if="msg.imageUrl" :src="msg.imageUrl" alt="Generated Image" class="generated-image">
          <!-- 发布到小红书按钮 -->
          <el-button v-if="msg.imageUrl" type="primary" size="small" class="upload-btn"
            @click="showXiaohongshuUploadDialog(msg.imageUrl, index)">
            发布到小红书
          </el-button>
        </div>
      </div>

      <!-- 加载动画 -->
      <div v-if="isLoading" class="message-wrapper ai-message">
        <div class="avatar">
          <img src="@/views/AI/images/ai-avatar.png" alt="AI Avatar">
        </div>
        <div class="message loading">
          <div class="loading-dot"></div>
          <div class="loading-dot"></div>
          <div class="loading-dot"></div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input">
      <el-input v-model="inputMessage" type="textarea" placeholder="请输入消息..." :rows="3"
        @keyup.enter="sendMessage"></el-input>
      <div class="input-actions">
        <el-button icon="Microphone" circle size="small" @click="startVoiceInput"></el-button>
        <el-button type="primary" @click="sendMessage">发送</el-button>
      </div>
    </div>
    <!-- 快手上传弹窗 -->
    <el-dialog v-model="uploadDialogVisible" title="上传到快手" width="500px">
      <div class="dialog-content">
        <p>视频路径: {{ currentVideoUrl }}</p>
        <p>封面路径: {{ coverImageUrl }}</p>
        <p>视频名称: {{ videoName }}</p>
        <el-input v-model="videoSummary" placeholder="请输入视频标签" type="textarea" :rows="2" class="mt-2"></el-input>
        <p class="text-sm text-gray-500 mt-1">提示: 可以使用 #校园生活回忆 #青春校园故事 #学生时代 等标签</p>
        <el-input v-model="talkInput" placeholder="请输入话题内容，多个话题用逗号分隔" class="mt-3"></el-input>
        <el-input v-model="atUsersInput" placeholder="请输入@用户，多个用户用逗号分隔" class="mt-3"></el-input>
      </div>
      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="uploadToKuaishou">确认上传</el-button>
      </template>
    </el-dialog>
    <!-- 抖音上传弹窗 -->
    <el-dialog v-model="douyinUploadDialogVisible" title="发布到抖音" width="500px">
      <div class="dialog-content">

        <p>视频路径: {{ douyinCurrentVideoUrl }}</p>
        <p>封面路径: {{ douyinCoverImageUrl }}</p>
        <p>视频标题: {{ douyinTitle }}</p>
        <el-input v-model="douyinSummary" placeholder="请输入视频描述" type="textarea" :rows="3" class="mt-2"></el-input>
        <el-input v-model="douyinTalkInput" placeholder="请输入话题内容，多个话题用逗号分隔" class="mt-3"></el-input>
        <p class="text-sm text-gray-500 mt-1">提示: 可以使用 #生活记录 #春天来了 #樱花季 #Vlog日常 等话题</p>
      </div>
      <template #footer>
        <el-button @click="douyinUploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="uploadToDouyin">确认发布</el-button>
      </template>
    </el-dialog>
    <!-- 小红书上传弹窗 -->
    <el-dialog v-model="xiaohongshuUploadDialogVisible" title="发布到小红书" width="500px">
      <div class="dialog-content">
        <p v-if="!xiaohongshuIsVideoUpload">图片路径: {{ xiaohongshuCurrentImageUrl }}</p>
        <p v-else>视频路径: {{ xiaohongshuCurrentVideoUrl }}</p>
        <p>图片标题: {{ xiaohongshuTitle }}</p>
        <el-input v-model="xiaohongshuSummary" placeholder="请输入图片描述" type="textarea" :rows="3" class="mt-2"></el-input>
        <el-input v-model="xiaohongshuTagsInput" placeholder="请输入标签，多个标签用逗号分隔" class="mt-3"></el-input>
        <p class="text-sm text-gray-500 mt-1">提示: 可以使用 #生活记录 #美食分享 #旅行日记 #穿搭推荐 等标签</p>

        // 添加新字段
        <el-select v-model="xiaohongshuContentType" placeholder="请选择内容类型" class="mt-3">
          <el-option label="笔记" value="note"></el-option>
          <el-option label="视频" value="video"></el-option>
          <el-option label="图文" value="image_text"></el-option>
        </el-select>

        <el-select v-model="xiaohongshuPermission" placeholder="请选择权限设置" class="mt-3">
          <el-option label="公开" value="public"></el-option>
          <el-option label="私有" value="private"></el-option>
          <el-option label="仅粉丝可见" value="followers_only"></el-option>
        </el-select>

        <el-input v-model="xiaohongshuAuthorStatement" placeholder="请输入作者声明" type="textarea" :rows="2"
          class="mt-3"></el-input>
        <p class="text-sm text-gray-500 mt-1">提示: 可以填写原创声明、内容说明等信息</p>
      </div>
      <template #footer>
        <el-button @click="xiaohongshuUploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="uploadToXiaohongshu">确认发布</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
// 导入视频生成API
import { generateVideo, getVideoResult, generateVideoComplete } from '@/api/video/index';
// 导入图片生成API
import { generateImageComplete } from '@/api/image/index';
// 导入对话API（已创建）
import { chatCompletion } from '@/api/chat/index';
// 导入快手上传API
import { uploadToKuaishouAPI } from '@/api/video/kuaishou';
// 导入抖音上传API（假设存在）
import { uploadToDouyinAPI } from '@/api/video/douyin'; // 添加抖音API导入
// 导入小红书上传API（假设存在）
import { uploadToXiaohongshuAPI } from '@/api/image/xiaohongshu'; // 添加小红书API导入
// 导入Element Plus组件
import { ElMessage } from 'element-plus';

// 定义消息类型
interface Message {
  content: string;
  isUser: boolean;
  videoUrl?: string; // 可选的视频URL字段
  imageUrl?: string; // 新增：可选的图片URL字段
  coverUrl?: string; // 新增：视频封面URL字段
}

// 状态管理
const messages = ref<Message[]>([]);
const inputMessage = ref('');
const isLoading = ref(false);
const chatContent = ref<HTMLDivElement | null>(null);
const isListening = ref(false);
// 上传弹窗相关状态
const uploadDialogVisible = ref(false);
// 移除重复定义的 douyinUploadDialogVisible
const currentVideoUrl = ref('');
const coverImageUrl = ref('');
const videoName = ref('');
const videoSummary = ref('#校园生活回忆 #青春校园故事 #学生时代');
const talkInput = ref('');
const atUsersInput = ref('');
// 抖音上传弹窗相关状态
const douyinUploadDialogVisible = ref(false);
const douyinCurrentVideoUrl = ref('');
const douyinCoverImageUrl = ref('');
const douyinTitle = ref('哈喽123');
const douyinSummary = ref('春天来了，樱花开了，记录下这美好的一刻。阳光正好，微风不燥，这样的日子真想一直延续下去。');
const douyinTalkInput = ref('#生活记录,#春天来了,#樱花季,#Vlog日常');
// 小红书上传弹窗相关状态
const xiaohongshuUploadDialogVisible = ref(false);
const xiaohongshuCurrentImageUrl = ref('');
const xiaohongshuTitle = ref('');
const xiaohongshuSummary = ref('分享一张美图');
const xiaohongshuTagsInput = ref('#生活记录,#日常分享');
// 添加新字段的响应式变量
const xiaohongshuContentType = ref('note'); // 默认内容类型为笔记
const xiaohongshuPermission = ref('public'); // 默认权限为公开
const xiaohongshuAuthorStatement = ref(''); // 作者声明默认为空
const xiaohongshuCurrentVideoUrl = ref('');
const xiaohongshuCurrentCoverUrl = ref('');
const xiaohongshuIsVideoUpload = ref(false);
const currentMessageIndex = ref(-1);
let recognition: any = null;
let silenceTimer: ReturnType<typeof setTimeout> | null = null;
let pollTimer: ReturnType<typeof setTimeout> | null = null;

// 初始化语音识别
const initSpeechRecognition = () => {
  if ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window) {
    recognition = new ((window as any).SpeechRecognition || (window as any).webkitSpeechRecognition)();
    recognition.continuous = true;
    recognition.interimResults = true;
    recognition.lang = 'zh-CN'; // 设置为中文识别
  }
};

// 开始语音输入
const startVoiceInput = () => {
  if (!recognition) {
    initSpeechRecognition();
    if (!recognition) {
      inputMessage.value = '您的浏览器不支持语音识别功能';
      return;
    }
  }

  isListening.value = true;
  inputMessage.value = '正在聆听...';

  // 重置静音计时器
  resetSilenceTimer();

  recognition.onresult = (event: any) => {
    const transcript = Array.from(event.results)
      .map((result: any) => result[0])
      .map(result => result.transcript)
      .join('');

    inputMessage.value = transcript;
    resetSilenceTimer(); // 有声音输入，重置计时器
  };

  recognition.onerror = (event: any) => {
    console.error('语音识别错误:', event.error);
    isListening.value = false;
    clearSilenceTimer();
  };

  recognition.onend = () => {
    isListening.value = false;
    clearSilenceTimer();
    if (inputMessage.value && inputMessage.value !== '正在聆听...') {
      // 如果有识别结果，自动发送
      sendMessage();
    }
  };

  recognition.start();
};

// 重置静音计时器
const resetSilenceTimer = () => {
  clearSilenceTimer();
  silenceTimer = setTimeout(() => {
    if (recognition && isListening.value) {
      recognition.stop();
    }
  }, 3000); // 3秒无声音自动停止
};

// 清除静音计时器
const clearSilenceTimer = () => {
  if (silenceTimer) {
    clearTimeout(silenceTimer);
    silenceTimer = null;
  }
};

// 清除轮询计时器
const clearPollTimer = () => {
  if (pollTimer) {
    clearTimeout(pollTimer);
    pollTimer = null;
  }
};

// 生成随机封面URL
const generateRandomCoverUrl = (): string => {
  // 这里使用picsum.photos提供的随机图片服务
  // 你也可以替换为自己的图片服务或默认封面
  const width = 1080;
  const height = 1920;
  const randomId = Math.floor(Math.random() * 1000);
  return `https://picsum.photos/${width}/${height}?random=${randomId}`;
};

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim()) return;

  // 保存用户输入的内容
  const userMessage = inputMessage.value.trim();

  // 添加用户消息
  messages.value.push({
    content: userMessage,
    isUser: true
  });

  // 清空输入框
  inputMessage.value = '';

  // 滚动到底部
  scrollToBottom();

  // 显示加载状态
  isLoading.value = true;

  // 判断用户需求，是生成视频还是图片
  const hasImageKeyword = userMessage.includes('图片');
  const hasVideoKeyword = userMessage.includes('视频');
  const hasGenerateKeyword = userMessage.includes('生成');

  if (hasGenerateKeyword) {
    if (hasImageKeyword && hasVideoKeyword) {
      // 同时提到图片和视频，提示用户明确需求
      messages.value.push({
        content: `您的请求中同时包含了生成图片和视频的需求，请明确您想要生成哪种类型的内容？`,
        isUser: false
      });
      isLoading.value = false;
      scrollToBottom();
    } else if (hasImageKeyword) {
      // 调用图片生成完整流程
      generateImageComplete(userMessage)
        .then(result => {
          if (result && result[0] && result[0].url) {
            messages.value.push({
              content: `图片生成完成！点击下方查看图片:`,
              isUser: false,
              imageUrl: result[0].url
            });
          } else {
            messages.value.push({
              content: `图片生成失败或超时`,
              isUser: false
            });
          }
          isLoading.value = false;
          scrollToBottom();
        })
        .catch(error => {
          messages.value.push({
            content: `图片生成失败`,
            isUser: false
          });
          isLoading.value = false;
          scrollToBottom();
        });
    } else if (hasVideoKeyword) {
      // 调用视频生成完整流程
      generateVideoComplete(userMessage)
        .then(result => {
          if (result && result[0] && result[0].url) {
            // 提取视频类型关键词用于生成名称
            const extractVideoType = (input: string): string => {
              const keywords = input.split(/[\s，。！？]/).filter(word => word.trim());
              return keywords.length > 0 ? keywords[0] : '默认视频';
            };
            const videoType = extractVideoType(userMessage);
            messages.value.push({
              content: `视频生成完成！点击下方播放视频:`,
              isUser: false,
              videoUrl: result[0].url,
              coverUrl: result[0].coverUrl || generateRandomCoverUrl()
            });
          } else {
            messages.value.push({
              content: `视频生成失败或超时`,
              isUser: false
            });
          }
          isLoading.value = false;
          scrollToBottom();
        })
        .catch(error => {
          messages.value.push({
            content: `视频生成失败`,
            isUser: false
          });
          isLoading.value = false;
          scrollToBottom();
        });
    } else {
      // 提到了生成但没有明确类型，提示用户
      messages.value.push({
        content: `您提到了"生成"，但未明确是生成图片还是视频，请补充说明。`,
        isUser: false
      });
      isLoading.value = false;
      scrollToBottom();
    }
  } else {
    // 没有提到生成，调用对话API回答问题
    chatCompletion(userMessage)
      .then(result => {
        if (result && result.success && result.data && result.data.reply) {
          messages.value.push({
            content: result.data.reply,
            isUser: false
          });
        } else {
          messages.value.push({
            content: `抱歉，我无法回答这个问题。${result?.message ? ' ' + result.message : ''}`,
            isUser: false
          });
        }
        isLoading.value = false;
        scrollToBottom();
      })
      .catch(error => {
        messages.value.push({
          content: `对话请求失败`,
          isUser: false
        });
        isLoading.value = false;
        scrollToBottom();
      });
  }
};

// 显示上传弹窗(快手)
const showUploadDialog = async (videoUrl: string, index: number) => {
  currentVideoUrl.value = videoUrl;
  currentMessageIndex.value = index;

  let coverUrl = generateRandomCoverUrl();
  // 临时实现 validateCoverUrl 函数，通过创建 Image 对象检查 URL 是否有效
  const validateCoverUrl = async (url: string): Promise<boolean> => {
    return new Promise((resolve) => {
      const img = new Image();
      img.src = url;
      img.onload = () => resolve(true);
      img.onerror = () => resolve(false);
    });
  };
  let isValid = await validateCoverUrl(coverUrl);

  // 如果URL无效，重试生成
  let retryCount = 0;
  while (!isValid && retryCount < 3) {
    coverUrl = generateRandomCoverUrl();
    isValid = await validateCoverUrl(coverUrl);
    retryCount++;
  }

  coverImageUrl.value = isValid ? coverUrl : 'https://picsum.photos/640/360';
  // 临时实现 extractVideoType 函数，简单提取第一个关键词作为视频类型
  const extractVideoType = (input: string): string => {
    const keywords = input.split(/[\s，。！？]/).filter(word => word.trim());
    return keywords.length > 0 ? keywords[0] : '默认视频';
  };
  const videoType = extractVideoType(messages.value[index - 1].content);
  videoName.value = `${videoType}_视频`;
  videoSummary.value = '#校园生活回忆 #青春校园故事 #学生时代';
  talkInput.value = ''; // 重置话题输入
  atUsersInput.value = ''; // 重置@用户输入
  uploadDialogVisible.value = true;
};

// 上传到快手
const uploadToKuaishou = async () => {
  try {
    isLoading.value = true;
    uploadDialogVisible.value = false;

    // 处理话题输入，转换为数组
    const talkArray = talkInput.value
      ? talkInput.value.split(',').map(item => item.trim()).filter(Boolean)
      : [];

    // 处理@用户输入，转换为数组
    const atUsersArray = atUsersInput.value
      ? atUsersInput.value.split(',').map(item => item.trim()).filter(Boolean)
      : [];

    // 准备上传数据
    const uploadData = {
      command: 'publish',
      platform: 'kuaishouhao',
      params: {
        video: currentVideoUrl.value,
        cover: coverImageUrl.value,
        summary: videoSummary.value || '#校园生活回忆 #青春校园故事 #学生时代',
        talk: talkArray, // 使用处理后的话题数组
        at_users: atUsersArray // 使用处理后的@用户数组
      }
    };

    console.log('上传到快手的数据:', uploadData);

    await uploadToKuaishouAPI(uploadData);

    ElMessage({
      message: '发布成功',
      type: 'success'
    });
  } catch (error) {
    ElMessage({
      message: '发布失败',
      type: 'error'
    });
  } finally {
    isLoading.value = false;
  }
};

// 显示上传弹窗(抖音)
const showDouyinUploadDialog = async (videoUrl: string, index: number) => {
  douyinCurrentVideoUrl.value = videoUrl;
  currentMessageIndex.value = index;

  let coverUrl = generateRandomCoverUrl();
  // 临时实现 validateCoverUrl 函数，通过创建 Image 对象检查 URL 是否有效
  const validateCoverUrl = async (url: string): Promise<boolean> => {
    return new Promise((resolve) => {
      const img = new Image();
      img.src = url;
      img.onload = () => resolve(true);
      img.onerror = () => resolve(false);
    });
  };
  let isValid = await validateCoverUrl(coverUrl);

  // 如果URL无效，重试生成
  let retryCount = 0;
  while (!isValid && retryCount < 3) {
    coverUrl = generateRandomCoverUrl();
    isValid = await validateCoverUrl(coverUrl);
    retryCount++;
  }

  douyinCoverImageUrl.value = isValid ? coverUrl : 'https://picsum.photos/640/360';
  // 提取视频标题
  const extractVideoTitle = (input: string): string => {
    const keywords = input.split(/[，。！？]/).filter(word => word.trim());
    return keywords.length > 0 ? keywords[0] : '抖音视频';
  };
  // 获取用户输入的内容作为标题来源
  const titleSource = messages.value[index - 1].content;
  douyinTitle.value = extractVideoTitle(titleSource);
  douyinSummary.value = '记录美好生活瞬间';
  douyinTalkInput.value = '#生活记录,#日常vlog';
  douyinUploadDialogVisible.value = true;
};

// 上传到抖音
const uploadToDouyin = async () => {
  try {
    isLoading.value = true;
    douyinUploadDialogVisible.value = false;

    // 处理话题输入，转换为数组
    const talkArray = douyinTalkInput.value
      ? douyinTalkInput.value.split(',').map(item => item.trim()).filter(Boolean)
      : [];

    // 准备上传数据
    const uploadData = {
      command: 'postVideo',
      platform: 'douyin',
      params: {
        title: douyinTitle.value,
        video: douyinCurrentVideoUrl.value,
        cover: douyinCoverImageUrl.value,
        talk: talkArray,
        summary: douyinSummary.value,
        post_id: `post_${Date.now()}` // 生成临时post_id
      }
    };

    console.log('发布到抖音的数据:', uploadData);

    await uploadToDouyinAPI(uploadData);

    ElMessage({
      message: '发布成功',
      type: 'success'
    });
  } catch (error) {
    ElMessage({
      message: '发布失败',
      type: 'error'
    });
  } finally {
    isLoading.value = false;
  }
};

// 显示小红书上传弹窗
const showXiaohongshuUploadDialog = async (imageUrl: string, index: number) => {
  xiaohongshuCurrentImageUrl.value = imageUrl;
  currentMessageIndex.value = index;
  xiaohongshuIsVideoUpload.value = false; // 添加这行来重置状态

  // 验证图片URL有效性
  const validateImageUrl = async (url: string): Promise<boolean> => {
    return new Promise((resolve) => {
      const img = new Image();
      img.src = url;
      img.onload = () => resolve(true);
      img.onerror = () => resolve(false);
    });
  };

  let isValid = await validateImageUrl(imageUrl);

  // 如果URL无效，提示用户
  if (!isValid) {
    ElMessage.error('图片URL无效，请重试');
    return;
  }

  // 提取图片标题
  const extractImageTitle = (input: string): string => {
    const keywords = input.split(/[，。！？]/).filter(word => word.trim());
    return keywords.length > 0 ? keywords[0] : '小红书图片';
  };
  // 获取用户输入的内容作为标题来源
  const titleSource = messages.value[index - 1].content;
  xiaohongshuTitle.value = extractImageTitle(titleSource);
  xiaohongshuSummary.value = '分享一张美图';
  xiaohongshuTagsInput.value = '#生活记录,#日常分享';
  xiaohongshuUploadDialogVisible.value = true;
};

// 显示小红书视频上传弹窗
const showXiaohongshuVideoUploadDialog = async (videoUrl: string, coverUrl: string, index: number) => {
  xiaohongshuCurrentVideoUrl.value = videoUrl;
  xiaohongshuCurrentCoverUrl.value = coverUrl;
  currentMessageIndex.value = index;
  xiaohongshuIsVideoUpload.value = true;

  // 验证视频URL有效性
  const validateVideoUrl = async (url: string): Promise<boolean> => {
    return new Promise((resolve) => {
      const video = document.createElement('video');
      video.src = url;
      video.onloadedmetadata = () => resolve(true);
      video.onerror = () => resolve(false);
    });
  };

  // 验证封面URL有效性
  const validateCoverUrl = async (url: string): Promise<boolean> => {
    return new Promise((resolve) => {
      const img = new Image();
      img.src = url;
      img.onload = () => resolve(true);
      img.onerror = () => resolve(false);
    });
  };

  const isVideoValid = await validateVideoUrl(videoUrl);
  const isCoverValid = await validateCoverUrl(coverUrl);

  if (!isVideoValid) {
    ElMessage.error('视频URL无效，请重试');
    return;
  }

  if (!isCoverValid) {
    ElMessage.error('封面URL无效，已使用随机封面');
    // 调用生成随机封面的函数
    xiaohongshuCurrentCoverUrl.value = generateRandomCoverUrl();
  }

  // 提取视频标题
  const extractVideoTitle = (input: string): string => {
    const keywords = input.split(/[，。！？]/).filter(word => word.trim());
    return keywords.length > 0 ? keywords[0] : '小红书视频';
  };
  // 获取用户输入的内容作为标题来源
  const titleSource = messages.value[index - 1].content;
  xiaohongshuTitle.value = extractVideoTitle(titleSource);
  xiaohongshuSummary.value = '分享一个视频';
  xiaohongshuTagsInput.value = '#生活记录,#日常分享';
  xiaohongshuUploadDialogVisible.value = true;
};

// 上传到小红书
const uploadToXiaohongshu = async () => {
  try {
    isLoading.value = true;
    xiaohongshuUploadDialogVisible.value = false;

    // 验证标题是否为空
    if (!xiaohongshuTitle.value.trim()) {
      throw new Error('标题不能为空');
    }

    // 处理标签输入，转换为数组
    const tagsArray = xiaohongshuTagsInput.value
      ? xiaohongshuTagsInput.value.split(',').map(item => item.trim()).filter(Boolean)
      : [];

    // 准备上传数据
    const uploadData = {
      command: 'publish',
      platform: 'xiaohongshu',
      params: {
        title: xiaohongshuTitle.value,
        summary: xiaohongshuSummary.value,
        talk: tagsArray,
        permission: 1,
        author_statement: true
      }
    };

    // 根据上传类型添加不同的参数
    if (xiaohongshuIsVideoUpload.value) {
      // 视频上传参数
      uploadData.params.content_type = 'video';
      uploadData.params.video = xiaohongshuCurrentVideoUrl.value;
      uploadData.params.cover = xiaohongshuCurrentCoverUrl.value;
    } else {
      // 图文上传参数
      uploadData.params.content_type = 'news';
      uploadData.params.images = xiaohongshuCurrentImageUrl.value;
    }

    console.log('发布到小红书的数据:', uploadData);

    const result = await uploadToXiaohongshuAPI(uploadData);

    ElMessage({
      message: '发布成功',
      type: 'success'
    });

    // 重置视频上传标志，确保不影响下次上传
    xiaohongshuIsVideoUpload.value = false;
  } catch (error) {
    ElMessage({
      message: '发布失败',
      type: 'error'
    });
    // 出错时也重置视频上传标志
    xiaohongshuIsVideoUpload.value = false;
  } finally {
    isLoading.value = false;
  }
};

// 滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    if (chatContent.value) {
      chatContent.value.scrollTop = chatContent.value.scrollHeight;
    }
  }, 100);
};

// 组件挂载时初始化
onMounted(() => {
  initSpeechRecognition();
  scrollToBottom();
});

// 组件卸载时清理

onUnmounted(() => {
  clearSilenceTimer();
  clearPollTimer();
  if (recognition && recognition.abort) {
    recognition.abort();
  }
});
</script>

<style scoped lang="scss">
/* 科技风格基础变量 */
$tech-bg-dark: #0a0e17;
$tech-bg: #12192c;
$tech-primary: #00f0ff;
$tech-secondary: #7b61ff;
$tech-accent: #ff2a6d;
$tech-text: #e0e0ff;
$grid-color: rgba(0, 240, 255, 0.1);
$glow-primary: 0 0 10px $tech-primary, 0 0 20px rgba(0, 240, 255, 0.3);
$glow-secondary: 0 0 10px $tech-secondary, 0 0 20px rgba(123, 97, 255, 0.3);

/* 聊天容器样式 */
.ai-chat-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: $tech-bg-dark;
  background-image:
    linear-gradient($grid-color 1px, transparent 1px),
    linear-gradient(90deg, $grid-color 1px, transparent 1px);
  background-size: 20px 20px;
  position: relative;
  overflow: hidden;
}

/* 扫描线效果 */
.ai-chat-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background-color: rgba(0, 240, 255, 0.5);
  box-shadow: $glow-primary;
  animation: scanLine 3s linear infinite;
  z-index: 1;
}

/* 聊天头部样式 */
.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: rgba(18, 25, 44, 0.8);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid $tech-primary;
  box-shadow: 0 2px 10px rgba(0, 240, 255, 0.1);
  position: relative;
  z-index: 2;
}

.chat-title {
  font-size: 16px;
  font-weight: bold;
  color: $tech-primary;
  text-shadow: 0 0 5px $tech-primary;
}

.chat-actions {
  display: flex;
  gap: 8px;
}

.chat-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background-color: rgba(18, 25, 44, 0.5);
  backdrop-filter: blur(5px);
  position: relative;
  z-index: 1;
}

.message-wrapper {
  display: flex;
  margin-bottom: 16px;
  animation: fadeIn 0.3s ease;
  position: relative;
}

.user-message {
  flex-direction: row-reverse;
}

.ai-message {
  flex-direction: row;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  margin: 0 10px;
  border: 2px solid $tech-primary;
  box-shadow: $glow-primary;
  position: relative;
  z-index: 2;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 8px;
  word-break: break-word;
  line-height: 1.5;
  position: relative;
  z-index: 2;
}

.user-message .message {
  background-color: rgba(123, 97, 255, 0.2);
  color: $tech-text;
  border: 1px solid $tech-secondary;
  box-shadow: $glow-secondary;
  backdrop-filter: blur(2px);
}

.ai-message .message {
  background-color: rgba(0, 240, 255, 0.1);
  color: $tech-text;
  border: 1px solid $tech-primary;
  box-shadow: 0 0 5px rgba(0, 240, 255, 0.2);
  backdrop-filter: blur(2px);
}

/* 视频播放器样式 */
.video-player {
  width: 100%;
  margin-top: 10px;
  border-radius: 4px;
  border: 1px solid $tech-primary;
  box-shadow: $glow-primary;
  transition: all 0.3s ease;
}

.video-player:hover {
  transform: scale(1.01);
  box-shadow: 0 0 15px $tech-primary, 0 0 30px rgba(0, 240, 255, 0.4);
}

/* 上传按钮样式 */
.upload-btn {
  margin-top: 10px;
  margin-right: 10px;
  background-color: transparent;
  border: 1px solid $tech-primary;
  color: $tech-primary;
  transition: all 0.3s ease;
}

.upload-btn:hover {
  background-color: $tech-primary;
  color: $tech-bg-dark;
  box-shadow: $glow-primary;
}

/* 弹窗内容样式 */
.dialog-content {
  background-color: rgba(18, 25, 44, 0.9);
  border: 1px solid $tech-primary;
  border-radius: 8px;
  padding: 16px;
  box-shadow: $glow-primary;
  color: $tech-text;

  p {
    margin-bottom: 10px;
  }
}

.chat-input {
  padding: 12px 16px;
  background-color: rgba(18, 25, 44, 0.8);
  backdrop-filter: blur(10px);
  border-top: 1px solid $tech-primary;
  box-shadow: 0 -2px 10px rgba(0, 240, 255, 0.1);
  position: relative;
  z-index: 2;
}

.input-actions {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.loading {
  display: flex;
  gap: 8px;
  padding: 12px;
}

.loading-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  animation: pulse 1.4s infinite ease-in-out both;
}

.loading-dot:nth-child(1) {
  background-color: $tech-primary;
  box-shadow: 0 0 10px $tech-primary;
  animation-delay: -0.32s;
}

.loading-dot:nth-child(2) {
  background-color: $tech-secondary;
  box-shadow: 0 0 10px $tech-secondary;
  animation-delay: -0.16s;
}

.loading-dot:nth-child(3) {
  background-color: $tech-accent;
  box-shadow: 0 0 10px $tech-accent;
}

/* 动画定义 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {

  0%,
  80%,
  100% {
    transform: scale(0);
  }

  40% {
    transform: scale(1);
  }
}

@keyframes scanLine {
  0% {
    top: -3px;
  }

  100% {
    top: 100%;
  }
}

/* 图片样式 */
.generated-image {
  width: 100%;
  margin-top: 10px;
  border-radius: 4px;
  border: 1px solid $tech-primary;
  box-shadow: $glow-primary;
  transition: all 0.3s ease;
}

.generated-image:hover {
  transform: scale(1.01);
  box-shadow: 0 0 15px $tech-primary, 0 0 30px rgba(0, 240, 255, 0.4);
}

.text-sm {
  font-size: 12px;
  color: rgba(224, 224, 255, 0.7);
}

.text-gray-500 {
  color: rgba(224, 224, 255, 0.5);
}

/* 滚动条样式 */
.chat-content::-webkit-scrollbar {
  width: 6px;
}

.chat-content::-webkit-scrollbar-track {
  background: rgba(18, 25, 44, 0.5);
}

.chat-content::-webkit-scrollbar-thumb {
  background: $tech-primary;
  border-radius: 3px;
  box-shadow: $glow-primary;
}

.chat-content::-webkit-scrollbar-thumb:hover {
  background: $tech-secondary;
  box-shadow: $glow-secondary;
}

/* 输入框样式增强 */
.el-textarea__inner {
  background-color: rgba(18, 25, 44, 0.5);
  border: 1px solid $tech-primary;
  color: $tech-text;
  transition: all 0.3s ease;
}

.el-textarea__inner:focus {
  border-color: $tech-secondary;
  box-shadow: $glow-secondary;
}

/* 按钮样式增强 */
.el-button {
  background-color: transparent;
  border: 1px solid $tech-primary;
  color: $tech-primary;
  transition: all 0.3s ease;
}

.el-button:hover {
  background-color: $tech-primary;
  color: $tech-bg-dark;
  box-shadow: $glow-primary;
}

.el-button--primary {
  background-color: $tech-primary;
  border-color: $tech-primary;
  color: $tech-bg-dark;
  box-shadow: $glow-primary;
}

.el-button--primary:hover {
  background-color: $tech-secondary;
  border-color: $tech-secondary;
  box-shadow: $glow-secondary;
}

/* 弹窗标题样式 */
.el-dialog__title {
  color: $tech-primary;
  text-shadow: 0 0 5px $tech-primary;
}

/* 弹窗背景半透明 */
.el-overlay {
  background-color: rgba(10, 14, 23, 0.8);
  backdrop-filter: blur(5px);
}
</style>
